import 'package:shared_preferences/shared_preferences.dart';

///
///Author: YoungChan
///Date: 2019/8/29 12:49
///Description: 缓存处理工具类，因为SharedPreference 只有单例模式，大量使用容易引起key的冲突，
///             所以单独封装一层，统一处理防止key冲突，
///params： group  定义缓存key所属的group，进一步分出一个层级防止key冲突, 必传参数
///         key 缓存的key
///         value 缓存的value
///

class NDCache {
  static Future<bool> exist(String group, String key) async {
    var sp = await SharedPreferences.getInstance();
    return Future.value(sp.containsKey('#$group\_$key'));
  }

  static setString(String group, String key, String? value) {
    if (value != null) {
      SharedPreferences.getInstance().then((sp) {
        sp.setString('#$group\_$key', value);
      });
    }
  }

  static Future<String?> getString(String group, String key) async {
    var sp = await SharedPreferences.getInstance();
    return Future.value(sp.getString('#$group\_$key'));
  }

  static setStringList(String group, String key, List<String>? value) {
    if (value != null) {
      SharedPreferences.getInstance().then((sp) {
        sp.setStringList('#$group\_$key', value);
      });
    }
  }

  static Future<List<String>?> getStringList(String group, String key) async {
    var sp = await SharedPreferences.getInstance();
    return Future.value(sp.getStringList('#$group\_$key'));
  }

  static setBool(String group, String key, bool value) {
    SharedPreferences.getInstance().then((sp) {
      sp.setBool('#$group\_$key', value);
    });
  }

  static Future<bool> getBool(String group, String key) async {
    var sp = await SharedPreferences.getInstance();
    return Future.value(sp.getBool('#$group\_$key') ?? false);
  }

  static setNum(String group, String key, num? value) {
    if (value != null) {
      SharedPreferences.getInstance().then((sp) {
        if (value is double) {
          sp.setDouble('#$group\_$key', value);
        } else if (value is int) {
          sp.setInt('#$group\_$key', value);
        }
      });
    }
  }

  static Future<num?> getNum(String group, String key) async {
    var sp = await SharedPreferences.getInstance();
    return Future.value(sp.get('#$group\_$key') as num?);
  }

  static void remove(String group, String key) {
    SharedPreferences.getInstance().then((sp) {
      sp.remove('#$group\_$key');
    });
  }

  static void clear(String group) {
    SharedPreferences.getInstance().then((sp) {
      var keyList = <String>[];
      sp.getKeys().forEach((k) {
        if (k.contains('#$group\_')) {
          keyList.add(k);
        }
      });
      keyList.forEach((k) {
        sp.remove(k);
      });
    });
  }
}
